const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const AnnouncementSchema = new Schema({
  title: { type: String, required: true },
  content: { type: String, required: true },
  createdAt: { type: Date, default: Date.now },
});

const LeaveSchema = new Schema({
  startDate: { type: Date, required: true },
  endDate: { type: Date, required: true },
  reason: { type: String, required: true },
  status: { type: String, enum: ['pending', 'approved', 'rejected'], default: 'pending' },
  approver: { type: Schema.Types.ObjectId, ref: 'User' },
  createdAt: { type: Date, default: Date.now },
});

const ChildrenDepartmentSchema = new Schema({
    name: { type: String, required: true },
    users: [
      {
        user: { type: Schema.Types.ObjectId, ref: 'User' },
        jobTitle: { type: String },
        leaveRequests: [LeaveSchema],
        tasks: [{ type: Schema.Types.ObjectId, ref: 'Task' }],
      },
    ],
    isTopDepartment:{type:Boolean,default:false,require:true},
    announcements: [AnnouncementSchema],
    departmentCreater:{type:String,default:null,required:false},
    departmentDescription:{type:String,default:null,required:false},
    departmentEmail:{type:String,default:null,required:false},
    departmentPhoneNumber:{type:String,default:null,required:false},
    createdAt: { type: Date, default: Date.now },
    updatedAt: { type: Date },
  });
  
const DepartmentSchema = new Schema({
    name: { type: String, required: true },
    users: [
      {
        user: { type: Schema.Types.ObjectId, ref: 'User' },
        jobTitle: { type: String },
        leaveRequests: [LeaveSchema],
        tasks: [{ type: Schema.Types.ObjectId, ref: 'Task' }],
      },
    ],
    isTopDepartment:{type:Boolean,default:true,require:true},
    announcements: [AnnouncementSchema],
    children: [ChildrenDepartmentSchema],
    departmentCreater:{type:String,default:null,required:false},
    departmentDescription:{type:String,default:null,required:false},
    departmentEmail:{type:String,default:null,required:false},
    departmentPhoneNumber:{type:String,default:null,required:false},
    createdAt: { type: Date, default: Date.now },
    updatedAt: { type: Date, default: Date.now },
  });
  
  DepartmentSchema.pre('save', function (next) {
    this.updatedAt = new Date();
    next();
  });

module.exports = mongoose.model('Department', DepartmentSchema);
